﻿using Avalonia.Collections;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using ExCSS;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore.Metadata;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using MsBox.Avalonia.Enums;
using Tmds.DBus.Protocol;
using 畜牧业审核程序国产.Models;
using 畜牧业审核程序国产.Models.RagModel;
using 畜牧业审核程序国产.Models.RagModel.JsonObject.TrainedTongyiJsonObject;
using 畜牧业审核程序国产.Models.ToolsClass;
using static SkiaSharp.HarfBuzz.SKShaper;
using Debug = 畜牧业审核程序国产.Models.RagModel.JsonObject.TrainedTongyiJsonObject.Debug;


namespace 畜牧业审核程序国产.ViewModels
{
    internal partial class ChatWindowViewModel : ObservableObject
    {

        private readonly HttpClient? _httpClient;
        private string HistoryMessageTableNameInDB = "大语言模型历史消息";

        ////private string _apiEndpoint = "https://api.qwen.aliyun.com/v1/chat/completions"; // 可替换为不同的 API 端点
        //private string _apiKey = "sk-4487d1c2764d4c388af7a241ed28c7f4"; // 可替换为其他 API 密钥
        //private string _apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 请求URL,又称为endPoint
        ////private string _apiUrl = "https://dashscope.aliyuncs.com/api/v1/apps/c08d698e5e9e48d7bf36cc184ac8df10/completion";
        //private string _ragModel = "通义千问";
        private string _apiKey = null;
        private string _apiUrl = null;
        private string _ragModel = null;


        //用户按下摁钮后,先跳出来一个小窗口,让用户自己选择用哪个模型.view都是chatWindow,只是在上面显示的模型名称不一样

        //[ObservableProperty]
        //private AvaloniaList<string> messages = new AvaloniaList<string>();//要转成string


        private string _currentChatModel;
        public string CurrentChatModel
        {
            get => "当前大语言模型: " + _ragModel;
        }
        private string _title;
        public string Title
        {
            get =>   _ragModel+"对话界面";
            set => SetProperty(ref _title, value);
        }
        private ObservableCollection<KeyValuePair<string, (string, string)>> _ragValueTurple = new ObservableCollection<KeyValuePair<string, (string, string)>>();
      
        public ObservableCollection<KeyValuePair<string, (string, string)>> RagValueTurpleCln
        {
            get => _ragValueTurple;
        }

        private KeyValuePair<string, (string, string)> _selectedTurple;

        public KeyValuePair<string, (string, string)> SelectedTurple
        {
            get { return _selectedTurple; }
            set {
                SetProperty(ref _selectedTurple, value);
            }
        }





        [ObservableProperty]
        private string _userInput;

        public RelayCommand ClearCommand { get; private set; }
        public RelayCommand DeriveToExcelCommand { get; private set; }
        public RelayCommand DeleteAllMessagesCommand { get; private set; }
        public RelayCommand OpenAnotherRagChatViewCommand { get; private set; }
        public RelayCommand<string> OpenDocReferencesViewComand { get; private set; }

        /// <summary>
        /// 目前传进来的ragModel包括"通义千问业务知识库"、“RagFlow知识库”、“通义千问普通模型”、“通义千问统计法律知识库”
        /// </summary>
        /// <param name="apiKey"></param>
        /// <param name="apiUrl"></param>
        /// <param name="ragModel"></param>
        #region  构造函数
        public ChatWindowViewModel(string apiKey, string apiUrl, string ragModel)
        {
            this._apiKey = apiKey;
            this._apiUrl = apiUrl;
            this._ragModel = ragModel;
            //WeakReferenceMessenger.Default.Register<TransmitAPIMsgs>(this, OnMyMessageReceived);
            MessagesInChatWindow = new ObservableCollection<MessageShowInChatItem>();
            AddMessages(ragModel);
            this.ClearCommand = new RelayCommand(() => ClearInputAndSelected());
            //this.SendMessageCommand = new AsyncRelayCommand(async () => await SendMessageAsync(ragModel));
            this.DeriveToExcelCommand = new RelayCommand(async () =>await DeriveToExcel());
            this.DeleteAllMessagesCommand = new RelayCommand(async ()=>await DeleteAllMessagesOfThisRagModel());
            //WeakReferenceMessenger.Default.Register<TransmitView>(this,OnMyMessageReceived);//暂时没用

            this.RagValueTurpleCln.Add(new KeyValuePair<string, (string, string)>("通义千问业务知识库", ("sk-4487d1c2764d4c388af7a241ed28c7f4", "https://dashscope.aliyuncs.com/api/v1/apps/c08d698e5e9e48d7bf36cc184ac8df10/completion")));
            this.RagValueTurpleCln.Add(new KeyValuePair<string, (string, string)>("通义千问统计法律知识库", ("sk-4487d1c2764d4c388af7a241ed28c7f4", "https://dashscope.aliyuncs.com/api/v1/apps/0190dd7b5b6943b88e5e9b1592c43279/completion")));
            this.RagValueTurpleCln.Add(new KeyValuePair<string, (string, string)>("通义千问普通模型", ("sk-4487d1c2764d4c388af7a241ed28c7f4", "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")));

            this.OpenAnotherRagChatViewCommand = new RelayCommand(() => {
                if (SelectedTurple.Key != null)
                {
                    var chatWindow = new ChatWindow(SelectedTurple.Value.Item1, SelectedTurple.Value.Item2, SelectedTurple.Key);
                    chatWindow.Show();
                }
            });
            this.OpenDocReferencesViewComand = new RelayCommand<string>((str) => OpenDocReferencesView(str));
        }
        public ChatWindowViewModel()
        {
            
        }
        private void OpenDocReferencesView(string? str)
        {
            DocReferencesView docReferencesView = new DocReferencesView(str);
            docReferencesView.Show();
        }

        private ChatWindow _chatWindow = null;
        //private void OnMyMessageReceived(object recipient, TransmitView transmitedWindow)
        //{
        //    if (transmitedWindow.TransmitedWindow is ChatWindow)
        //    {
        //        _chatWindow =transmitedWindow.TransmitedWindow as ChatWindow;
        //    }
        //}
        #endregion


        private ObservableCollection<MessageShowInChatItem> _messagesInChatWindow = new ObservableCollection<MessageShowInChatItem>();

        public ObservableCollection<MessageShowInChatItem> MessagesInChatWindow
        {
            get => _messagesInChatWindow;
            set => SetProperty(ref _messagesInChatWindow, value);
        }

        private void ClearInputAndSelected()
        {
            UserInput = string.Empty;
            if (MessagesInChatWindow != null && MessagesInChatWindow.Count > 0)
            {
                for (int i = 0; i < MessagesInChatWindow.Count; i++)
                {
                    MessagesInChatWindow[i].IsSelected = false;
                }

            }
        }
        //通义千问普通模型的api调用,从此网站进入:https://help.aliyun.com/zh/model-studio/developer-reference/use-qwen-by-calling-api?spm=a2c4g.11186623.0.0.2b39b0a8LNdVUi#a89e2e62f99yw
        //请求json:
        //string jsonContent = @"{
        //     ""model"": ""qwen-plus"",
        //     ""messages"": [
        //         {
        //             ""role"": ""system"",
        //             ""content"": ""You are a helpful assistant.""
        //         },
        //         {
        //             ""role"": ""user"", 
        //             ""content"": ""你是谁？""
        //         }
        //     ]
        // }";
        //接收到的响应json
        //{
        //    "choices": [
        //    {
        //        "message": {
        //            "role": "assistant",
        //            "content": "我是阿里云开发的一款超大规模语言模型，我叫通义千问。"
        //        },
        //        "finish_reason": "stop",
        //        "index": 0,
        //        "logprobs": null
        //    }
        //    ],
        //    "object": "chat.completion",
        //    "usage": {
        //        "prompt_tokens": 22,
        //        "completion_tokens": 17,
        //        "total_tokens": 39
        //    },
        //    "created": 1726127645,
        //    "system_fingerprint": null,
        //    "model": "qwen-plus",
        //    "id": "chatcmpl-81951b98-28b8-9659-ab07-cd30d25600e7"
        //}
        //自己训练的通义千问知识库的api调用,从此网站进入:https://bailian.console.aliyun.com/?spm=5176.28197581.0.0.1be629a44xp2yr#/app-center/assistant/c08d698e5e9e48d7bf36cc184ac8df10?tabKey=share
        //请求json
        //单轮对话:
        //jsonContent = @"{
        //        ""input"": {
        //            ""prompt"": ""你是谁？""
        //        },
        //        ""parameters"": {},
        //        ""debug"": {}
        //    }";
        //多轮对话:


        /// <summary>
        /// 
        /// </summary>
        /// <param name="ragModel"></param>
        private void AddMessages(string ragModel)
        {
            try
            {

                StaticLogger.SystemInfo("往界面加入消息");
                // 添加测试消息
                //MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, "User", DateTime.Now.ToString(), "Hello!"));
                if (ragModel.Contains("通义千问普通模型"))
                {
                    MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, _currentChatModel,
                        DateTime.Now.ToString(), $"当前大语言模型为{ragModel},请输入您的问题" + @"<br>" + "***样例问题:***" + @"<br>" + "** 1.C#是什么？**" + @"<br>" + "** 1.Avalonia框架是什么？**"));
                }
               else if (ragModel.Contains("通义千问")==true && ragModel.Contains("业务"))
               {
                   MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, _currentChatModel,
                       DateTime.Now.ToString(), $"当前大语言模型为{ragModel},请输入您的问题" + @"<br>" + "***样例问题:***" + @"<br>" + "** 1.请给出生猪出栏指标解释。**" +
                                                @"<br>" + "** 2.根据知识库中浙江省畜牧业形势分析给我一份类似的提纲。**" + @"<br>" + "** 3.根据知识库中的内容写一份市级畜牧业形势分析提纲。**"
                                                + @"<br>" + " **4.生猪PSY指的是什么？**"));
                }
                else if (ragModel.Contains("通义千问")&& ragModel.Contains("统计法"))
                {
                    MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, _currentChatModel,
                        DateTime.Now.ToString(), $"当前大语言模型为{ragModel},请输入您的问题" + @"<br>" + "***样例问题:***" + @"<br>" + "** 1.请给出两道执法证考试题目。**" +
                                                 @"<br>" + "** 2.新修订统计法对县级统计机构的工作要求是什么?**" + @"<br>" + "** 3.新修订统计法对领导干部的要求有哪些?**" + @"<br>" + "** 4.新修订统计法新增和修改的内容有哪些?**"));

                }
                CreateHistoryChatMessageTableInDataBase(ragModel);
                List<ChatMessageFromDB> recently10HistoryChatMessageList = GetRecentlyChatMessages(ragModel, 10);
                if (recently10HistoryChatMessageList == null || recently10HistoryChatMessageList.Count == 0)
                {
                    return;
                }

                if (ragModel.Contains("通义千问普通模型"))
                {
                    for (int i = 0; i < recently10HistoryChatMessageList.Count; i++)
                    {
                        ChatMessageFromDB singleHistoryMessage = recently10HistoryChatMessageList[i];
                        if (singleHistoryMessage.Role.Equals("user"))
                        {
                            MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel,
                                singleHistoryMessage.Role, singleHistoryMessage.Timestamp,
                                singleHistoryMessage.Content));
                        }
                        else
                        {
                            MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, _ragModel,
                                singleHistoryMessage.Timestamp, singleHistoryMessage.Content));
                        }
                    }
                }
                else //if(ragModel.Contains("通义千问")&& ragModel.Contains("知识库"))
                {
                    for (int i = 0; i < recently10HistoryChatMessageList.Count; i++)
                    {
                        ChatMessageFromDB chatMessage = recently10HistoryChatMessageList[i];
                        if (chatMessage.Role.Equals("user"))
                        {
                            MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, chatMessage.Role,
                                chatMessage.Timestamp, chatMessage.Content));
                        }
                        else
                        {

                            MessagesInChatWindow.Add(new MessageShowInChatItem(CurrentChatModel, _ragModel,
                                chatMessage.Timestamp, chatMessage.Content, false, chatMessage.SeesionId,chatMessage.DocReferences));
                        }
                    }
                    MessagesInChatWindow[MessagesInChatWindow.Count - 1].IsSelected = true;
                }
                
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError(
                    $"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
            }
        }
        //public void AddMessage(string sender, DateTime timestamp, string content, bool isUserMessage)
        //{
        //    MessagesInChat.Add(new MessageShowInChatItem(sender, timestamp, content, isUserMessage));
        //    // Scroll to the bottom of the ListBox after adding a message

        //   //{
        //   //    onloading.Show();
        //   //});
        //   //Dispatcher.UIThread.Post(() =>
        //   // {
        //   //     MessagesListBox?.ScrollIntoView(Messages.Last());
        //   // });
        //}






        [RelayCommand]
        private async Task SendMessageAsync()//string ragModel)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(UserInput))
                    return;
                //等应答返回且不出错的情况下,才把用户的问题写入到数据库中
                //InsertMessageToHistory("user", UserInput, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ms"), ragModel);//这里传入的是时间戳还是这个时间的形式?要测试一下
                var userMessage = new MessageShowInChatItem()
                {
                    ChatModel = CurrentChatModel,
                    Sender = "user",
                    Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Content = UserInput,
                    IsSelected = false,
                    //HorizontalAlignment = "right"
                };
                //对话窗体上显示用户的输入内容
                MessagesInChatWindow.Add(userMessage);

                //将用户输入窗口清空.因为string类型是引用类型,所以如果直接清空的话,会导致传给api的用户内容为空,因此需要用一个中间变量进行传递
                string inputValue = $"{UserInput} ".Trim();
                UserInput = string.Empty;

                //显示进度条
                OnLoadingBar _progressBar = new OnLoadingBar();
                _progressBar.Show();
                var progress = new Progress<int>(value => _progressBar.UpdateProgress(value));
                await Task.Run(() => { OnLoadingBarExecute.OnLoadingBar(progress); });

                #region 根据不同的api接口构建不同的请求json

                if (_ragModel.Equals("通义千问普通模型"))
                {
                    //从数据库中查询到最近的历史对话消息,两条对话,即4条记录
                    List<ChatMessageFromDB> recent4HistoryAndNowInputChatMessages =
                        GetRecentlyChatMessages(_ragModel, 4);
                    //在数据库获取的历史对话消息后面加上用户当前的提问内容,形成当前会话
                    recent4HistoryAndNowInputChatMessages.Add(new ChatMessageFromDB("user", inputValue,
                        DateTime.Now.ToString(), null,null));
                    //将系统消息和当前会话合并.系统消息在前,当前会话在后
                    var messages = new List<ChatMessageFromDB>
                    {
                        new ChatMessageFromDB { Role = "system", Content = "You are a helpful assistant." }
                    };
                    messages.AddRange(recent4HistoryAndNowInputChatMessages);

                    // 构建请求数据
                    var requestData = new
                    {
                        model = "qwen-plus",
                        messages = messages.Select(m => new { role = m.Role, content = m.Content }).ToArray()
                    };

                    // 序列化为 JSON 字符串
                    string jsonContent = JsonSerializer.Serialize(requestData,
                        new JsonSerializerOptions { WriteIndented = true });


                    //向api请求并接收数据
                    try
                    {
                        string result =
                            await Models.RagModel.ApiService.SendPostRequestAsync(_apiUrl, jsonContent, _apiKey);

                        if (result.Contains("请求失败"))
                        {
                            var apiMessage = new MessageShowInChatItem()
                            {
                                ChatModel = CurrentChatModel,
                                Sender = _ragModel,
                                Timestamp = "请求失败",
                                Content = result,
                                //HorizontalAlignment = "left"
                            };
                            MessagesInChatWindow.Add(apiMessage);
                        }
                        else
                        {
                            //反序列化JSON字符串到相应的对象
                            var objectResult = JsonSerializer.Deserialize<RootObject>(result);
                            //把long类型的created秒级时间戳转成时间
                            long unixTimestampInSeconds = objectResult.created.Value;
                            DateTime createDateTimeOfJson = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                                .AddSeconds(unixTimestampInSeconds).ToLocalTime();
                            string createTimeOfJsonStr = createDateTimeOfJson.ToString("yyyy-MM-dd HH:mm:ss:ms");
                            string? messageContent = objectResult.choices[0].message.content;
                            var apiMessage = new MessageShowInChatItem()
                            {
                                ChatModel = CurrentChatModel,
                                Sender = _ragModel,
                                Timestamp = createTimeOfJsonStr,
                                Content = messageContent,
                                //HorizontalAlignment = "left"
                            };
                            MessagesInChatWindow.Add(apiMessage);
                            _progressBar.Close();
                            //把信息加入到数据库中
                            InsertMessageToHistory(_ragModel, "user", userMessage.Content, userMessage.Timestamp, null,null);
                            InsertMessageToHistory(_ragModel, "assistant", apiMessage.Content, apiMessage.Timestamp,null,
                                null);
                        }
                    }
                    catch (Exception ex)
                    {
                        var apiMessage = new MessageShowInChatItem()
                        {
                            ChatModel = CurrentChatModel,
                            Sender = _ragModel,
                            Timestamp = "请求出错",
                            Content = ex.Message,
                            //HorizontalAlignment = "left"
                        };
                        MessagesInChatWindow.Add(apiMessage);
                        _progressBar.Close();
                    }




                }
                else if (_ragModel.Contains("通义千问") && _ragModel.Contains("知识库"))
                {



                    var selectedMessageInChatWindow = MessagesInChatWindow.Where(m => m.IsSelected).ToArray();
                    if (selectedMessageInChatWindow.Length > 1)
                    {
                        await MyMessagebox.Show("同时选中的历史消息多于1条,只能选中一条历史消息!");
                        MessagesInChatWindow.Remove(MessagesInChatWindow[MessagesInChatWindow.Count - 1]);
                        _progressBar.Close();
                        return;
                    }

                    if (selectedMessageInChatWindow.Length == 1 && selectedMessageInChatWindow[0].Sender == "user")
                    {
                        await MyMessagebox.Show("不能选中自己发送的消息作为历史消息!");
                        MessagesInChatWindow.Remove(MessagesInChatWindow[MessagesInChatWindow.Count - 1]);
                        _progressBar.Close();
                        return;
                    }

                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
                        //client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");这是给流式输出用的
                        string jsonContent = null;
                        string jsonContent2 = null;
                        if (selectedMessageInChatWindow == null || selectedMessageInChatWindow.Length == 0)
                        {
                            jsonContent = string.Format(@"{{
                ""input"": {{
                    ""prompt"": ""{0}""
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}", inputValue);
                        }
                        else
                        {
                            jsonContent = string.Format(@"{{
    ""input"": {{
        ""prompt"": ""{0}"",
        ""session_id"": ""{1}""
    }},
    ""parameters"": {{}},
    ""debug"": {{}}
}}", inputValue, selectedMessageInChatWindow[0].SessionId);
                            //    var requestData = new TrainedTongyiRequestJsonContent
                            //    {
                            //        Input = new Input()
                            //        {
                            //            Prompt = inputValue,
                            //            SessionId = selectedMessageInChatWindow[0].SessionId
                            //        },
                            //        Parameters = new Parameters(),
                            //        Debug = new Debug(),
                            //    };
                            //   jsonContent2 = JsonSerializer.Serialize(requestData, new JsonSerializerOptions
                            //    {
                            //        WriteIndented = true // 格式化输出，便于阅读
                            //    });
                        }


                        HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                        try
                        {
                            HttpResponseMessage response = await client.PostAsync(_apiUrl, content);
                            MessageShowInChatItem apiMessage = null;
                            if (response.IsSuccessStatusCode)
                            {
                                string responseBody = await response.Content.ReadAsStringAsync();
                                var trainedTongyiResponse =
                                    JsonSerializer.Deserialize<TrainedTongyiResponse>(responseBody);
                                var docReferences = trainedTongyiResponse.Output.DocReferences;

                                if (docReferences == null || docReferences.Count == 0)
                                {
                                    apiMessage = new MessageShowInChatItem()
                                    {
                                        ChatModel = CurrentChatModel,
                                        Sender = _ragModel,
                                        Timestamp = DateTime.Now.ToString(),
                                        Content = trainedTongyiResponse.Output.Text,
                                        IsSelected = false,
                                        SessionId = trainedTongyiResponse.Output.SessionId,
                                        DocReferences = "无"
                                        //HorizontalAlignment = "left"
                                    };
                                    MessagesInChatWindow.Add(apiMessage);
                                    _progressBar.Close();
                                    InsertMessageToHistory(_ragModel, "user", userMessage.Content, userMessage.Timestamp,
                                        "userInput", "无");
                                    InsertMessageToHistory(_ragModel, _ragModel, apiMessage.Content,
                                        DateTime.Now.ToString(), apiMessage.SessionId,"无");


                                }
                                else
                                {
                                    string docRerencesInfo = null;
                                    for (int i = 0; i < docReferences.Count; i++)
                                    {
                                        docRerencesInfo += $"-----------[{docReferences[i].IndexId}]------------" +
                                                           Environment.NewLine + docReferences[i].Text +
                                                           Environment.NewLine;
                                    }

                                    apiMessage = new MessageShowInChatItem()
                                    {
                                        ChatModel = CurrentChatModel,
                                        Sender = _ragModel,
                                        Timestamp = DateTime.Now.ToString(),
                                        Content = trainedTongyiResponse.Output.Text,
                                        //+ Environment.NewLine +
                                        //          Environment.NewLine + "以下是回答的文档来源信息:" + Environment.NewLine +
                                        //          Environment.NewLine + docRerencesInfo,
                                        IsSelected = false,
                                        SessionId = trainedTongyiResponse.Output.SessionId,
                                        DocReferences = docRerencesInfo
                                    };
                                    MessagesInChatWindow.Add(apiMessage);
                                    _progressBar.Close();
                                    InsertMessageToHistory(_ragModel, "user", userMessage.Content, userMessage.Timestamp,
                                        "userInput", "无");
                                    InsertMessageToHistory(_ragModel, _ragModel, apiMessage.Content,
                                        DateTime.Now.ToString(), apiMessage.SessionId, docRerencesInfo);
                                    Console.WriteLine("Request successful:");
                                    Console.WriteLine(responseBody);
                                }

                              
                            }
                            else
                            {
                                apiMessage = new MessageShowInChatItem()
                                {
                                    ChatModel = CurrentChatModel,
                                    Sender = _ragModel,
                                    Timestamp = DateTime.Now.ToString(),
                                    Content = $"出现错误,错误内容为:{response.Content.ReadAsStringAsync()}",
                                    IsSelected = false,

                                };
                                MessagesInChatWindow.Add(apiMessage);
                                _progressBar.Close();
                                Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                                string responseBody = await response.Content.ReadAsStringAsync();
                                Console.WriteLine(responseBody);
                            }

                            for (int i = 0; i < MessagesInChatWindow.Count; i++)
                            {
                                MessagesInChatWindow[i].IsSelected = false;
                            }

                            MessagesInChatWindow[MessagesInChatWindow.Count - 1].IsSelected = true;
                        }
                        catch (Exception ex)
                        {
                            MessageShowInChatItem apiMessage = new MessageShowInChatItem()
                            {
                                ChatModel = CurrentChatModel,
                                Sender = _ragModel,
                                Timestamp = DateTime.Now.ToString(),
                                Content = $"出现错误,错误内容为:{ex.Message}",
                                IsSelected = false,

                            };
                            MessagesInChatWindow.Add(apiMessage);
                            _progressBar.Close();
                            Console.WriteLine($"Error calling DashScope: {ex.Message}");
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError(
                    $"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
            }

            #endregion
                //从数据库中查询到最近的历史对话消息
            List<ChatMessageFromDB> recent10HistoryChatMessages = GetRecentlyChatMessages(_ragModel, 5);//两条之前的,加上用户刚刚新建的

            // List<ChatMessage> currentUserInputAndrecentHistoryChatMessages = recent10HistoryChatMessages.Concat(new[] { new ChatMessage("user", inputValue, DateTime.Now.ToString()) }).ToList();
            //构建请求数据,传给api并接收返回数据

            //var requestData = new
            //{
            //    message = recent10HistoryChatMessages.Select(
            //    m => new { role = m.Role, content = m.Content }).ToArray()
            //};
            //var jsonData = JsonSerializer.Serialize(requestData);







            ////把返回的数据写入到数据库中.
            //if (response.Key.Contains("请求出错") == false && response.Key.Contains("请求失败") == false)
            //{
            //    InsertMessageToHistory("assistant", response.Value, response.Key, ragModel);
            //}

        }

        public async Task<KeyValuePair<string, string>> SendRequestAsync(List<ChatMessageFromDB> recentHistoryChatMessageList)
        {
            ////使用转义双引号 ("") 来正确地表示 JSON 字符串
            //string jsonContent = @"
            //{
            //""model"": ""qwen-plus"",
            //""messages"":
            //[
            //    {
            //        ""role"": ""system"",
            //        ""content"": ""You are a helpful assistant.""
            //    },
            //    {
            //        ""role"": ""user"", 
            //        ""content"": """ + userInput + @"""
            //    }
            //]
            //}";

            //// 使用StringBuilder来构建JSON字符串，避免手动转义字符
            //var messages = new List<ChatMessage>
            //{
            //    new ChatMessage { Role = "system", Content = "You are a helpful assistant." }
            //};
            //messages.AddRange(recentHistoryChatMessageList);
            //var systemAndHistoryChatMessageList = messages;
            //var jsonBuilder = new System.Text.StringBuilder();
            //jsonBuilder.Append("{\n");
            //jsonBuilder.Append("  \"model\": \"qwen-plus\",\n");
            //jsonBuilder.Append("  \"messages\": [\n");

            //for (int i = 0; i < systemAndHistoryChatMessageList.Count; i++)
            //{
            //    jsonBuilder.Append("    {\n");
            //    jsonBuilder.AppendFormat("      \"role\": \"{0}\",\n", systemAndHistoryChatMessageList[i].Role);
            //    jsonBuilder.AppendFormat("      \"content\": \"{0}\"", systemAndHistoryChatMessageList[i].Content.Replace("\"", "\\\""));
            //    if (i != systemAndHistoryChatMessageList.Count - 1)
            //    {
            //        jsonBuilder.Append("\n    },\n");
            //    }
            //    else
            //    {
            //        jsonBuilder.Append("\n    }\n");
            //    }
            //}

            //jsonBuilder.Append("  ]\n");
            //jsonBuilder.Append("}");

            //string jsonContent = jsonBuilder.ToString();

            string jsonContent = await PrepareRequestDataAsync("qwen-plus", recentHistoryChatMessageList);

            try
            {
                string result = await Models.RagModel.ApiService.SendPostRequestAsync(_apiUrl, jsonContent, _apiKey);
                if (result.Contains("请求失败"))
                { return new KeyValuePair<string, string>("请求失败", result); }

                //反序列化JSON字符串到相应的对象
                var objectResult = JsonSerializer.Deserialize<RootObject>(result);
                //把long类型的created秒级时间戳转成时间
                long unixTimestampInSeconds = objectResult.created.Value;
                DateTime createDateTimeOfJson = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                            .AddSeconds(unixTimestampInSeconds).ToLocalTime();
                string createTimeOfJsonStr = createDateTimeOfJson.ToString("yyyy-MM-dd HH:mm:ss:ms");
                string? messageContent = objectResult.choices[0].message.content;
                KeyValuePair<string, string> createTimeAndMessageContent = new KeyValuePair<string, string>(createTimeOfJsonStr, objectResult.choices[0].message.content);
                return createTimeAndMessageContent;


            }
            catch (Exception ex)
            {
                return new KeyValuePair<string, string>("请求出错", ex.Message);
            }
        }
        //private async Task<string> SendRequestAsync(string prompt)
        //{
        //    //var content = new StringContent(JsonConvert.SerializeObject(new { query = userMessage }), Encoding.UTF8, "application/json");
        //    var content = new StringContent(
        //        JsonSerializer.Serialize(new { prompt }),
        //        System.Text.Encoding.UTF8,
        //        "application/json");

        //    _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");

        //    HttpResponseMessage response = await _httpClient.PostAsync(_apiKey, content);
        //    response.EnsureSuccessStatusCode();

        //    var responseBody = await response.Content.ReadAsStringAsync();
        //    var jsonResponse = JsonSerializer.Deserialize<JsonElement>(responseBody);

        //    // 一般 API 返回的是 JSON 格式，且包含 "choices" 字段，每个 choice 包含 "text"
        //    var choices = jsonResponse.GetProperty("choices").EnumerateArray();
        //    var result = string.Join("\n", choices.Select(choice => choice.GetProperty("text").GetString()));

        //    return result;
        //}
        private async Task<string> PrepareRequestDataAsync(string modelSymbol, List<ChatMessageFromDB> recentHistoryChatMessageList)
        {
            // 将历史消息和系统消息合并
            var messages = new List<ChatMessageFromDB>
    {
        new ChatMessageFromDB { Role = "system", Content = "You are a helpful assistant." }
    };
            messages.AddRange(recentHistoryChatMessageList);

            // 构建请求数据
            var requestData = new
            {
                model = modelSymbol,
                messages = messages.Select(m => new { role = m.Role, content = m.Content }).ToArray()
            };

            // 序列化为 JSON 字符串
            string jsonContent = JsonSerializer.Serialize(requestData, new JsonSerializerOptions { WriteIndented = true });

            return jsonContent;
        }
        private void CreateHistoryChatMessageTableInDataBase(string ragModel)
        {
            MyDBOperator chatOperator = MyDBOperator.DBOperatorInstance;
            bool isHistoryMessageTableExists = chatOperator.CheckIfTableExists($"{ragModel}HistoryMessages");
            if (!isHistoryMessageTableExists)
            {
                string sqlToCreateHistoryChatMessageTable = $"CREATE TABLE IF NOT EXISTS {ragModel}HistoryMessages " +
                    "(ID INTEGER PRIMARY KEY AUTOINCREMENT," +
                    "Role TEXT NOT NULL," +
                    "Content TEXT NOT NULL," +
                    " Timestamp TEXT NOT NULL,SessionId TEXT,DocReferences TEXT);";
                chatOperator.ExecuteBySql(sqlToCreateHistoryChatMessageTable);
            }
            else
            {
                DataTable dt = chatOperator.GetDataTable($"select * from {ragModel}HistoryMessages");
               string[] historyColumnNames =  chatOperator.GetColumnNamesArr(dt);
               if (historyColumnNames.Contains("DocReferences")==false)
               {
                   string alterTableSql = $"ALTER TABLE {ragModel}HistoryMessages ADD COLUMN DocReferences TEXT;";
                   chatOperator.ExecuteBySql(alterTableSql);
                }
            }
        }
        private void InsertMessageToHistory(string ragModel, string role, string content, string timestamp, string? sessionId,string? DocReferences)
        {
            using (var connection = new SqliteConnection($"Data Source={MyDBOperator._dbPath};"))
            {
                connection.Open();
                string tableName = $"{ragModel}HistoryMessages";
                string insertQuery;
                if (ragModel.Contains("通义千问普通模型"))
                {
                    insertQuery = $"INSERT INTO [{tableName}] (Role, Content, Timestamp) VALUES (@Role, @Content, @Timestamp)";
                    using (var command = new SqliteCommand(insertQuery, connection))
                    {
                        command.Parameters.AddWithValue("@Role", role);
                        command.Parameters.AddWithValue("@Content", content);
                        command.Parameters.AddWithValue("@Timestamp", timestamp);
                        command.ExecuteNonQuery();
                    }
                }
                else if (ragModel.Contains("通义千问") && ragModel.Contains("知识库"))
                {
                    if (DocReferences.Contains("----") == false)
                    {
                        insertQuery = $"INSERT INTO [{tableName}] (Role, Content, Timestamp, SessionId) VALUES (@Role, @Content, @Timestamp, @SessionId)";
                    }
                    else
                    {
                        insertQuery = $"INSERT INTO [{tableName}] (Role, Content, Timestamp, SessionId,DocReferences) VALUES (@Role, @Content, @Timestamp, @SessionId,@DocReferences)";
                    }
                   
                    using (var command = new SqliteCommand(insertQuery, connection))
                    {
                        command.Parameters.AddWithValue("@Role", role);
                        command.Parameters.AddWithValue("@Content", content);
                        command.Parameters.AddWithValue("@Timestamp", timestamp);
                        command.Parameters.AddWithValue("@SessionId", sessionId);
                        if (DocReferences != null)
                        {
                            command.Parameters.AddWithValue("@DocReferences", DocReferences);
                        }

                        command.ExecuteNonQuery();
                    }
                }
                else
                {
                    // Handle unexpected cases or throw an exception
                    throw new InvalidOperationException("Unexpected ragModel value");
                }
            }


            ////还是不用参数化查询了
            //MyDBOperator chatOperator = MyDBOperator.DBOperatorInstance;
            //if (ragModel.Contains("通义千问普通模型"))
            //{
            //    string sqlToInsertChatMessageToHistory = $"INSERT INTO {ragModel}HistoryMessages  (Role, Content, Timestamp) VALUES ('{role}', '{content}', '{timestamp}')";

            //    chatOperator.ExecuteBySql(sqlToInsertChatMessageToHistory);
            //}
            //else if (ragModel.Contains("通义千问") && ragModel.Contains("知识库"))
            //{
            //    string sqlToInsertChatMessageToHistory = $"INSERT INTO {ragModel}HistoryMessages  (Role, Content, Timestamp,SessionId) VALUES ('{role}', '{content}', '{timestamp}','{sessionId}')";

            //    chatOperator.ExecuteBySql(sqlToInsertChatMessageToHistory);
            //}


        }
        private List<ChatMessageFromDB> GetRecentlyChatMessages(string ragModel, int count = 10)
        {
            try
            {
                var chatMessagesList = new List<ChatMessageFromDB>();
                MyDBOperator chatOperator = MyDBOperator.DBOperatorInstance;
                if (ragModel.Contains("通义千问普通"))
                {
                    string sqlToGetRecentlyHistoryChatMessage = "WITH Top10Messages AS ( " +
                                                                " SELECT Role, Content, Timestamp, ID " +
                                                                $" FROM {ragModel}HistoryMessages " +
                                                                $"  ORDER BY ID DESC " +
                                                                $" LIMIT {count} ) " +
                                                                "SELECT Role, Content, Timestamp, ID FROM Top10Messages ORDER BY ID ASC";
                    DataTable dtOfRecentlyChatHistoryMessage =
                        chatOperator.GetDataTable(sqlToGetRecentlyHistoryChatMessage);
                    if (dtOfRecentlyChatHistoryMessage == null && dtOfRecentlyChatHistoryMessage.Rows.Count == 0)
                    {
                        return new List<ChatMessageFromDB>(); //返回一个空集合
                    }

                    for (int i = 0; i < dtOfRecentlyChatHistoryMessage.Rows.Count; i++)
                    {
                        //理论上来说,任何一行数据都不会为空,因此这里不做判断了
                        DataRow row = dtOfRecentlyChatHistoryMessage.Rows[i];
                        chatMessagesList.Add(new ChatMessageFromDB(row["Role"].ToString(),
                            row["Content"].ToString(),
                            row["Timestamp"].ToString(), null,null));
                    }

                    return chatMessagesList;
                }
                else if (ragModel.Contains("通义千问") && ragModel.Contains("知识库"))
                {
                    string sqlToGetRecentlyHistoryChatMessage = "WITH Top10Messages AS ( " +
                                                                " SELECT Role, Content, Timestamp,SessionId, ID,DocReferences " +
                                                                $" FROM {ragModel}HistoryMessages " +
                                                                $"  ORDER BY ID DESC " +
                                                                $" LIMIT {count} ) " +
                                                                "SELECT Role, Content, Timestamp,SessionId,DocReferences, ID FROM Top10Messages ORDER BY ID ASC";
                    DataTable dtOfRecentlyChatHistoryMessage =
                        chatOperator.GetDataTable(sqlToGetRecentlyHistoryChatMessage);
                    if (dtOfRecentlyChatHistoryMessage == null && dtOfRecentlyChatHistoryMessage.Rows.Count == 0)
                    {
                        return new List<ChatMessageFromDB>(); //返回一个空集合
                    }

                    for (int i = 0; i < dtOfRecentlyChatHistoryMessage.Rows.Count; i++)
                    {
                        //理论上来说,任何一行数据都不会为空,因此这里不做判断了
                        DataRow row = dtOfRecentlyChatHistoryMessage.Rows[i];
                        chatMessagesList.Add(new ChatMessageFromDB(row["Role"].ToString(),
                            row["Content"].ToString(),
                            row["Timestamp"].ToString(), row["SessionId"].ToString(), row["DocReferences"].ToString()));
                    }

                    return chatMessagesList;
                }
                else
                {
                    return new List<ChatMessageFromDB>(); //暂时返回一个空集合,后续有需要再添加
                }
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError(
                    $"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
                return new List<ChatMessageFromDB>(); //暂时返回一个空集合,后续有需要再添加
            }


        }

        //导出所有历史数据到Excel
        public async Task DeriveToExcel()
        {
            try
            {


                StaticLogger.SystemInfo("把历史数据导出到Excel");
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (var excelPackage = new ExcelPackage())
                {
                    MyDBOperator myDBOperator = MyDBOperator.DBOperatorInstance;
                    DataTable dt = myDBOperator.GetDataTable($"select * from {_ragModel}HistoryMessages ");
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        await MyMessagebox.Show("没有历史数据!", Icon.Warning);
                        return;
                    }

                    var sht = excelPackage.Workbook.Worksheets.Add($"{_ragModel}历史消息");
                    //写入表头
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        sht.Cells[1, i + 1].Value = dt.Columns[i].ColumnName;
                    }

                    //写入数据
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            sht.Cells[i + 2, j + 1].Value = dt.Rows[i][j];
                        }
                    }

                    var mainWindow = Global.GetMainWindow();
                    var topLevel = TopLevel.GetTopLevel(mainWindow);
                    var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions()
                    {
                        Title = "保存文件",
                        SuggestedFileName =
                            $"{_ragModel}历史消息(导出时间{DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒")}).xlsx",

                    });
                    if (file != null)
                    {
                        using (var steam = await file.OpenWriteAsync())
                        {
                            excelPackage.SaveAs(steam);
                        }

                        await MyMessagebox.Show("保存成功!", Icon.Success);//这里还是会跳到主界面
                    }
                }
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError(
                    $"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
            }
        }

        public async Task DeleteAllMessagesOfThisRagModel()
        {
            try
            {
                var answer =
                    await MyMessagebox.Show($"确定要删除{_ragModel}的所有本地历史记录吗?", ButtonEnum.OkCancel, Icon.Question);
                if (answer == ButtonResult.Cancel)
                {
                    return;
                }

                MyDBOperator deleteOperator = MyDBOperator.DBOperatorInstance;
                DataTable dt = deleteOperator.GetDataTable($"select * from {_ragModel}HistoryMessages ");
                if (dt == null || dt.Rows.Count == 0)
                {
                    await MyMessagebox.Show("没有历史数据!", Icon.Warning);
                    return;
                }

                deleteOperator.DeleteTable($"{_ragModel}HistoryMessages");
                await MyMessagebox.Show("删除成功", Icon.Success);
                MessagesInChatWindow.Clear();
                AddMessages(_ragModel);
            }
            catch (Exception ex)
            {
                StaticLogger.SystemError(
                    $"出现错误,错误信息{ex.Message},{Environment.NewLine}堆栈为{ex.StackTrace},{Environment.NewLine}对象为{ex.Source},{Environment.NewLine}方法为{ex.TargetSite}");
            }
        }

        

    }
}
